var big_img;
var main_img;
var big_img_width = 320;
var zoom_div_width = 100;
var half_zoom_div_width = zoom_div_width / 2;
var zoom_factor = 5 //放大五倍

var zoom_div = document.createElement("div");
zoom_div.classList.add("zoom");
var zoom_preview = document.createElement("div");
zoom_preview.classList.add("zoom-preview");

/** 获取大图url的函数，实现取决于实际场景 */
function getImgUrl(ele) {
    return ele.querySelector("img").src;
}





function main() {

    /** 我们不能监听big_img的鼠标移动事件，原因在于我们要在预览图中添加一个正方形框指示放缩位置，方框位于big_img之上导致big_img失去鼠标焦点无法响应 */
    document.addEventListener("mousemove", (e) => {
        let currX = 0;
        let currY = 0;
        let clientRect =  big_img.getClientRects()[0];
        //可能会有Bug。 我们获取big_img的绘制区域，计算鼠标位置在big_img内的相对位置。
        if (e.x > (clientRect.x + clientRect.width) || e.x < clientRect.x-1 || e.y > (clientRect.y + clientRect.height) || e.y < clientRect.y-1) {
            inOrOut = true;
            zoom_div.remove();
            zoom_preview.remove();
        }

        currX = e.x - clientRect.x;
        currY = e.y - clientRect.y;
        
        currX = Math.min(Math.max(half_zoom_div_width, currX), big_img_width - half_zoom_div_width);
        currY = Math.min(Math.max(half_zoom_div_width, currY), big_img_width - half_zoom_div_width);
        zoom_div.style.top = currY - half_zoom_div_width + "px";
        zoom_div.style.left = currX - half_zoom_div_width + "px";
        zoom_preview.style.backgroundPositionX = (half_zoom_div_width - currX) * zoom_factor + "px";
        zoom_preview.style.backgroundPositionY = (half_zoom_div_width - currY) * zoom_factor + "px";
    });

    big_img = document.querySelector("#big-img");
    main_img = document.querySelector("#main-img");
    main_img.addEventListener("mouseover", (_) => {
        console.log("mouseover");
        main_img.appendChild(zoom_div);
        zoom_preview.style ="background-image: url("+big_img.src+");";
        main_img.appendChild(zoom_preview);
    });
    document.querySelectorAll(".preview-img").forEach((ele) => {
        ele.addEventListener("click", () => {
            big_img.src = getImgUrl(ele);
        })
    });
}



document.addEventListener("DOMContentLoaded", main);